package idv.etrex.display 
{
	/**
	 * XGraphicsExecutor 可以將 xgraphics 儲存的指令執行到 igraphics 上
	 * @author etrex
	 */
	public class XGraphicsExecutor
	{
		private var igraphics :IGraphics;
		private var xgraphics :XGraphics;
		private var index:int;
			
		/**
		 * 是否已經到最後
		 */
		public function get isEnd():Boolean {			
			if (index < xgraphics.xml.children().length() )
				return false;
			else
				return true;
		}
		
		/**
		 * 建構式需要傳入一個 igraphics 和一個 xgraphics
		 * @param	ig 接受指令的物件
		 * @param	xg XGraphics指令
		 */
		public function XGraphicsExecutor(ig:IGraphics,xg:XGraphics) 
		{
			igraphics = ig;
			xgraphics = xg;
			index = 0;
		}
		
		/**
		 * 從頭開始
		 */
		public function reset():void {
			index = 0;
		}
		
		/**
		 * 執行下一個指令，並傳回是否已經執行到最後
		 */
		public function executeOne():Boolean {
			if (isEnd == false)
			{
				var xml:XML = xgraphics.xml.children()[index];
				executeXGraphics(xml);
				index ++;
			}
			return isEnd;
		}
		
		/**
		 * 執行到最後
		 */
		public function executeToEnd():void {			
			while (!executeOne());
		}
		
		/**
		 * 整個 xgraphics 從頭到尾執行一次，
		 * 不會影響 executeOne 和 executeToEnd
		 */
		public function executeAll():void {
			executeXGraphics(xgraphics.xml);
		}
		
		private function executeXGraphics(xml:XML):void {
			//for loop variable
			var x:XML;
			
			//XML Tag Name
			var xmlName:String = xml.name();
			
			//Recusive call
			if (xmlName == "XGraphics")
			{
				for each(x in xml.*)
					executeXGraphics(x);
			}
			
			//apply Function
			else if (igraphics[xmlName] is Function)
			{
				//Parse XML attribute XMLList to Array
				var array:Array = new Array();
				for each(x in xml.@*)
					array.push(x);
				
				//apply Function
				igraphics[xmlName].apply(igraphics, array);
			}
		}
	}

}